package com.stlm2.dems.service;

import com.google.gson.Gson;
import com.stlm2.core.common.md5.MD5;
import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.card.dao.CardDao;
import com.stlm2.dems.dao.*;

import com.stlm2.dems.entity.*;

import com.stlm2.dems.sns.dao.SmsDao;
import com.stlm2.dems.sns.entity.Sms;
import com.stlm2.dems.user.dao.*;
import com.stlm2.dems.user.entity.*;
import com.stlm2.util.Convert;
import com.stlm2.util.DingDanCode;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;

import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.util.Date;

import java.util.Map;
import java.util.UUID;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("userService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class UserService extends BaseServiceImpl<User> {

	@Resource
	private UserDao userDao;
    @Resource
	private Memcached memcached;
	@Resource
	private AccountDao accountDao;
	@Resource
	private DdmShopDao ddmShopDao;

	@Resource
	private CardDao cardDao;
	@Resource
	private FmsFlowDao fmsFlowDao;

	@Resource
	private UserRoleDao userRoleDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private LowerDao lowerDao;
	@Resource
	private SmsDao smsDao;
	@Resource
	private ConfigDao configDao;
	@Resource
	private ShopAdminUserDao shopAdminUserDao;

	@Resource
	private CollectionsDao collectionsDao;
	@Resource
	private FootMarkDao footMarkDao;
	@Resource
	private MessagesDao messagesDao;
	@Resource
	private PurchaseOrderDao purchaseOrderDao;
	@Resource
	private IntegralOrderDao integralOrderDao;
	@Override
	protected BaseDao <User> getDao() {
		return userDao;
	}

	public User getById(Integer id){
		return userDao.getById(id);
	}
    //通过用户账号（手机号）查询用户
	public User getByName(String name){
		return userDao.getByName(name);
	}
	//获得用户key
	public  String getUserKey(String userName){
		ModelMap model=new ModelMap();
		if(StringUtils.isEmpty(userName)){

			return  CodeContent.getModelByCode(0,"用户名不能为空",model);
		}
		try {
			 userName = new String(userName.getBytes("iso-8859-1"), "UTF-8");
		}catch (Exception e){
			e.printStackTrace();
		}

		String userKey;
		User user = userDao.getByName(userName);
		if(user==null){
			return  CodeContent.getModelByCode(0,"用户名不存在",model);
		}
		userKey = user.getUserKey();
		model.put("userKey",userKey);

		return  CodeContent.getModelByCode(1,"",model);
	}
    //通过传token 从缓存中取 用户
	public User getByToken(String token){
		User user = new User();
		if (token != null && !"".equals(token)) {
			Gson gson = new Gson();
			try {
				user = gson.fromJson(memcached.get(token).toString(), User.class);
			} catch (Exception e) {
				return null;
			}
		}else {
			return null;
		}
		return user;
	}
    //注册用户
	public User registerDo(String userName ,String upperUserId ,boolean isdzp,int companyCode){
		User user=new User();
		user.setName(userName);
		user.setCreateTime(new Date());
		user.setRealName(userName);
		String userKey= UUID.randomUUID().toString();
		user.setUserKey(userKey);
		String password= MD5.encryptMD5(userName + "12345987");
		user.setPassword(password);
		user.setUserState(UserState.Normal);
		user.setUserType(UserType.Normal);
		user.setUserLevel(UserLevel.Silver);
		user.setSex(Sex.Privacy);
		user.setCompanyCode(companyCode);
		userDao.add(user);
		int upperId=0;
		if(NumberUtils.isDigits(upperUserId)){
			upperId=NumberUtils.toInt(upperUserId);
		}
		User upperUser=userDao.getById(upperId);

		if(upperUser!=null){
			user.setUserUpper(upperUser.getUserUpper()+","+user.getId());
		}else {
			upperId=1;
			user.setUserUpper(1+","+user.getId());
		}

		userDao.modify(user);

		//上下级关系
		Lower lower=new Lower();
		lower.setUserId(upperId);
		lower.setLowerUserId(user.getId());
		lower.setState(true);
		lower.setCreateTime(new Date());
		lowerDao.add(lower);
		//userDao.userUpperLevel(1);
		//资金账户
		Account account=new Account();
		account.setAccountState(AccountState.Normal);
		account.setAccountType(AccountType.Customer);
		account.setAccountMoney(new BigDecimal(0));
		account.setAccountKey(userKey);
		account.setUserId(user.getId());
		account.setReducedJiFen(new BigDecimal(0));
		account.setRemainJiFen(new BigDecimal(0));
		account.setTotalJiFen(new BigDecimal(0));
		accountDao.add(account);
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			jedis.set("register:"+user.getId(),"2");
			if(isdzp){
				if(jedis.exists("DzpRegister:"+upperUser.getId())){
					jedis.incr("DzpRegister:"+upperUser.getId());
				}else {
					jedis.set("DzpRegister:"+upperUser.getId(),"1");
				}
				String value =jedis.get("DzpRegister:"+upperUser.getId());
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		return user;
	}

	public  void updateUser(User user,String token){
		if(user==null||token==null){
			return;
		}
		userDao.modify(user);
		Gson gson = new Gson();
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			String userToken = "token:" + user.getId();
			String tokenArr = jedis.get(userToken);
			if (tokenArr != null) {
				String[] tokenAr = tokenArr.split(":");
				for(int i=0;i<tokenAr.length;i++){
					memcached.set(tokenAr[i], 15*24*60*60, gson.toJson(user).toString());
				}
			}
	    }catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}


	}

	public Boolean isEmailExist(String email){
		return userDao.getByEmail(email).size() != 0 ? true : false;
	}
	public ModelMap buildModel(User user) {
		ModelMap model = new ModelMap();
		if(user != null){
			model.put("id",user.getId());
			model.put("name",user.getName());
			model.put("realName",user.getRealName());
			model.put("sexValue",user.getSexValue());
			model.put("sex",user.getSex()!= null?user.getSex().toString():"");
			model.put("email",user.getEmail()!= null?user.getEmail():"");
			model.put("avotorr",user.getAvotorr()!= null?user.getAvotorr():"");
			model.put("identity",user.getIdentity()!= null?user.getIdentity():"");
			model.put("qq",user.getQQ()!= null?user.getQQ():"");
			model.put("weixin",user.getWeixin()!= null?user.getWeixin():"");
			model.put("birthday",user.getBirthday()!=null? Convert.toShortYMD(user.getBirthday()):"");
		}
		return model;
	}

	public void test() {
//		User user=new User();
//		user.setName("事务测试1");
//		user.setRealName("cc");
//		user.setUserKey("ss");
//		user.setCreateTime(new Date());
//		user.setPassword("sss");
//		user.setUserState(UserState.Invalid);
//		user.setUserType(UserType.Admin);
//		user.setUserLevel(UserLevel.Silver);
//		user.setSex(Sex.Privacy);
//		userDao.add(user);
//		user.setUserUpper(7+","+user.getId());
//		userDao.modify(user);
//
//		//上下级关系
//		Lower lower=new Lower();
//		lower.setUserId(7);
//		lower.setLowerUserId(user.getId());
//		lower.setState(true);
//		lower.setCreateTime(new Date());
//		lowerDao.add(lower);
//		System.out.println("插入事务1");
//		int i=1/0;
//		user.setName("事务测试2");
//		user.setUserLevel(UserLevel.Silver);
//		user.setSex(Sex.Privacy);
//		userDao.add(user);
//		user.setUserUpper(7+","+user.getId());
//		userDao.modify(user);
//
//		//上下级关系
//		Lower lower2=new Lower();
//		lower2.setUserId(7);
//		lower2.setLowerUserId(user.getId());
//		lower2.setState(true);
//		lower2.setCreateTime(new Date());
//		lowerDao.add(lower);
//		System.out.println("插入事务2");
		//userDao.userUpperLevel(1);

	}

	/*
 *ZLQ
 * 个人中心中获取页面头部信息
 * token：用户token
  */
	public String getUserHeadData(ModelMap model,String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User user = userDao.getByToken(token);
		if (user == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser=userDao.getById(user.getId());
		Gson gson = new Gson();
		memcached.set(token, 15*24*60*60, gson.toJson(loginUser).toString());
		model.put("userId",loginUser.getId());
		model.put("Avotorr",loginUser.getAvotorr()!=null?loginUser.getAvotorr():"");
		model.put("RealName",loginUser.getRealName());
		Account account=accountDao.getByUserId(loginUser.getId());
		model.put("AccountMoney",account.getAccountMoney());
		//ffl  追加 数据  收藏记录数
		Integer collectionNum=collectionsDao.getCount(user.getId());
		model.put("collectionNum",collectionNum);
		//ffl  追加 数据    足迹记录数
		Integer footMarkNum=footMarkDao.getCount(user.getId());
		model.put("footMarkNum",footMarkNum);
		//ffl  追加 数据   未读消息记录数
		int count=messagesDao.getNotRead(user.getId());
		model.put("count", count);

		//获得用户待付款的订单数量
		int createNum = purchaseOrderDao.purchaseOrderNum(user.getId(),1);
		//获得用户待发货的订单数量
		int paymentNum = purchaseOrderDao.purchaseOrderNum(user.getId(),3);
		//获得用户待收货的订单数量
		int deliveriedNum = purchaseOrderDao.purchaseOrderNum(user.getId(),5);
		//获得用户待评价的订单数量
		int commentNum = purchaseOrderDao.purchaseOrderNum2(user.getId());
		model.put("createNum", createNum);
		model.put("paymentNum", paymentNum);
		model.put("deliveriedNum", deliveriedNum);
		model.put("commentNum", commentNum);
		return  CodeContent.getModelByCode(1, "", model);
	}

	public String getIntegralUserHeadData(ModelMap model,String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User user = userDao.getByToken(token);
		if (user == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser=userDao.getById(user.getId());
		Gson gson = new Gson();
		memcached.set(token, 15*24*60*60, gson.toJson(loginUser).toString());
		model.put("userId",loginUser.getId());
		model.put("Avotorr",loginUser.getAvotorr()!=null?loginUser.getAvotorr():"");
		model.put("RealName",loginUser.getRealName());
		Account account=accountDao.getByUserId(loginUser.getId());
		model.put("AccountMoney",account.getAccountMoney());

		BigDecimal integral=account.getRemainJiFen();
		model.put("integral",integral);


		//获得用户待付款的订单数量
		int createNum = integralOrderDao.integralOrderNum(user.getId(),1);
		//获得用户待发货的订单数量
		int paymentNum = integralOrderDao.integralOrderNum(user.getId(),3);
		//获得用户待收货的订单数量
		int deliveriedNum = integralOrderDao.integralOrderNum(user.getId(),5);
		//获得用户待评价的订单数量
		/*int commentNum = purchaseOrderDao.purchaseOrderNum2(user.getId());*/
		model.put("createNum", createNum);
		model.put("paymentNum", paymentNum);
		model.put("deliveriedNum", deliveriedNum);
		/*model.put("commentNum", commentNum);*/
		return  CodeContent.getModelByCode(1, "", model);
	}


	public  void  userTokenLoginCheck(String token,Integer userId){
		userDao.userTokenCheck(token,userId);
	}
	public void userTokenLogoutCheck(String token){
		User user=userDao.getByToken(token);
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			if(user!=null) {//缓存不过期
				String userToken = "token:" + user.getId();
				String tokenArr = jedis.get(userToken);
				System.out.println("logout=====tokenArr组合结果：" + tokenArr);
				if (tokenArr != null) {
					String[] tokenAr = tokenArr.split(":");
					if (tokenAr.length > 3) {//已经存入token数大于三个
						//需要删除第四个及以上的token
						for (int i = 3; i < tokenAr.length; i++) {
							memcached.delete(tokenAr[i]);
						}
						//剩下三个经行判断
						if (token.equals(tokenAr[0])) {
							String tokenArrr = tokenAr[1] + ":" + tokenAr[2];
							jedis.set(userToken, tokenArrr);
						}
						if (token.equals(tokenAr[1])) {
							String tokenArrr = tokenAr[0] + ":" + tokenAr[2];
							jedis.set(userToken, tokenArrr);
						}
						if (token.equals(tokenAr[2])) {
							String tokenArrr = tokenAr[0] + ":" + tokenAr[1];
							jedis.set(userToken, tokenArrr);
						}
					} else if (tokenAr.length == 3) {//缓存三个
						if (token.equals(tokenAr[0])) {
							String tokenArrr = tokenAr[1] + ":" + tokenAr[2];
							jedis.set(userToken, tokenArrr);
						}
						if (token.equals(tokenAr[1])) {
							String tokenArrr = tokenAr[0] + ":" + tokenAr[2];
							jedis.set(userToken, tokenArrr);
						}
						if (token.equals(tokenAr[2])) {
							String tokenArrr = tokenAr[0] + ":" + tokenAr[1];
							jedis.set(userToken, tokenArrr);
						}
					} else if (tokenAr.length == 2) {//缓存两个
						if (token.equals(tokenAr[0])) {
							jedis.set(userToken, tokenAr[1]);
						}
						if (token.equals(tokenAr[1])) {
							jedis.set(userToken, tokenAr[0]);
						}
					} else if (tokenAr.length == 1) {//缓存一个
						jedis.del(userToken);
					}
				}
				memcached.delete(token);
			}
			//user不存在 说明缓存已过期或者token为空/有误 无需 处理
		}catch (Exception e){
				e.printStackTrace();
			}
		finally {
				pool.returnResource(jedis);
		}


	}
/*
检验用户是否存在
 */
	public  String checkUserisEmpty(ModelMap modelMap,String userName){

		User user=userDao.getByName(userName);
		if(user!=null){
			modelMap.put("name",user.getName());
			modelMap.put("realName",user.getRealName());
			modelMap.put("id",user.getId());
		}else {
			return CodeContent.getModelByCode(0,"手机号不存在",modelMap);
		}
		return CodeContent.getModelByCode(1,"",modelMap);
	}
	/*
    系统自动注册用户
     */
	public  String registerUser(ModelMap modelMap,String userName,String companyCode){
		User user=new User();
		if(userDao.getByName(userName)==null){

			int companyC=1;
			if(NumberUtils.isDigits(companyCode)){
				companyC=NumberUtils.toInt(companyCode);
			}

			user.setName(userName);
			user.setCreateTime(new Date());
			user.setRealName(userName);
			String userKey= UUID.randomUUID().toString();
			user.setUserKey(userKey);
			String password= MD5.encryptMD5(userName + "12345987");
			user.setPassword(password);
			user.setUserState(UserState.Normal);
			user.setUserType(UserType.Normal);
			user.setUserLevel(UserLevel.Silver);
			user.setSex(Sex.Privacy);
			user.setCompanyCode(companyC);
			userDao.add(user);
			user.setUserUpper(1+","+user.getId());
			userDao.modify(user);

			//上下级关系
			Lower lower=new Lower();
			lower.setUserId(1);
			lower.setLowerUserId(user.getId());
			lower.setState(true);
			lower.setCreateTime(new Date());
			lowerDao.add(lower);
			//userDao.userUpperLevel(1);
			//资金账户
			Account account=new Account();
			account.setAccountState(AccountState.Normal);
			account.setAccountType(AccountType.Customer);
			account.setAccountMoney(new BigDecimal(0));
			account.setAccountKey(userKey);
			account.setUserId(user.getId());
			account.setReducedJiFen(new BigDecimal(0));
			account.setRemainJiFen(new BigDecimal(0));
			account.setTotalJiFen(new BigDecimal(0));
			accountDao.add(account);
			modelMap.put("name",user.getName());
			modelMap.put("realName",user.getRealName());
			modelMap.put("id",user.getId());
		}

		return CodeContent.getModelByCode(1,"",modelMap);
	}
	public  User OauthRegisterUser( String phone, String openId, String nickName,String headImgUrl,String type,String userId,Integer companyCode){
		User user=new User();
		if(userDao.getByName(phone)==null){
			user.setName(phone);
			user.setCreateTime(new Date());
			user.setRealName(nickName);
			String userKey= UUID.randomUUID().toString();
			user.setUserKey(userKey);
			String password= MD5.encryptMD5(phone + "12345987");
			user.setPassword(password);
			user.setUserState(UserState.Normal);
			user.setUserType(UserType.Normal);
			user.setUserLevel(UserLevel.Silver);
			user.setSex(Sex.Privacy);
			user.setAvotorr(headImgUrl);
			user.setCompanyCode(companyCode);
			if(OAuthType.QQ.toString().equals(type))
				user.setOpenId(openId);
			if(OAuthType.WX.toString().equals(type))
				user.setWxOpenId(openId);
			userDao.add(user);
			if(StringUtils.isEmpty(userId))
				user.setUserUpper(1+","+user.getId());
			else
				user.setUserUpper(userId+","+user.getId());
			userDao.modify(user);

			//上下级关系
			Lower lower=new Lower();
			lower.setUserId(1);
			lower.setLowerUserId(user.getId());
			lower.setState(true);
			lower.setCreateTime(new Date());
			lowerDao.add(lower);
			//userDao.userUpperLevel(1);
			//资金账户
			Account account=new Account();
			account.setAccountState(AccountState.Normal);
			account.setAccountType(AccountType.Customer);
			account.setAccountMoney(new BigDecimal(0));
			account.setAccountKey(userKey);
			account.setUserId(user.getId());
			account.setReducedJiFen(new BigDecimal(0));
			account.setRemainJiFen(new BigDecimal(0));
			account.setTotalJiFen(new BigDecimal(0));
			accountDao.add(account);
		}

		return user;
	}



	/*
	*创建后台用户
	* zlq
	* @param  token
	* @param  userAccount：新用户账号
	* @param  realName：新用户名字
	* @param  roleId：新用户角色ID
	* @param  phone:手机号
	 */
	public  ModelMap addUser(ModelMap map ,String token,String userAccount,String realName,String roleId,String phone,String companyCode){
		if (StringUtils.isEmpty(token)) {
			map.put("code",-1);
			map.put("msg","请登录");
			return map;
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			map.put("code",-1);
			map.put("msg","请登录");
			return map;
		}
		if (StringUtils.isEmpty(userAccount)) {
			map.put("code",0);
			map.put("msg","账号不能为空");
			return map;
		}
		if (StringUtils.isEmpty(realName)) {
			map.put("code",0);
			map.put("msg","名字不能为空");
			return map;
		}
		if (StringUtils.isEmpty(phone)) {
			map.put("code",0);
			map.put("msg","手机号不能为空");
			return map;
		}
		if (StringUtils.isEmpty(roleId)) {
			map.put("code",0);
			map.put("msg","角色不能为空");
			return map;
		}

		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"addUser" );
		if(o!=null){
			map.put("code",0);
			map.put("msg","您操作频繁，请在10秒后重试");
			return map;
		}else {
			memcached.set(loginUser.getId()+"addUser",10,"1");
		}
		Role role=roleDao.getById(Integer.parseInt(roleId));
		if(role==null){
			map.put("code",0);
			map.put("msg","角色ID不存在");
			return map;
		}
		if(role.getIsInit().equals(IsInit.NotAllow)){
			map.put("code",0);
			map.put("msg","该角色不允直接指定给用户");
			return map;
		}
		User newUser=userDao.getByName(userAccount);
		if(newUser!=null){
			map.put("code",0);
			map.put("msg","用户名已存在");
			return map;
		}
		int companyC=1;
		if(NumberUtils.isDigits(companyCode)){
			companyC=NumberUtils.toInt(companyCode);
		}
		newUser=new User();
		String password="123456";
		String md5Key = UUID.randomUUID().toString();
		String md5Password = MD5.encryptMD5(password.trim() + md5Key);

		newUser.setName(userAccount.trim());
		newUser.setCreateTime(new Date());
		newUser.setRealName(realName.trim());
		newUser.setUserKey(md5Key);
		newUser.setPassword(md5Password);
		newUser.setUserState(UserState.Normal);
		newUser.setUserType(UserType.Director);
		newUser.setSex(Sex.Privacy);
		newUser.setPhone(phone.trim());
		newUser.setUserLevel(UserLevel.Silver);
		newUser.setCompanyCode(companyC);
		userDao.add(newUser);
		newUser.setUserUpper(1+","+newUser.getId());
		userDao.modify(newUser);

		//上下级关系
		Lower lower=new Lower();
		lower.setUserId(1);
		lower.setLowerUserId(newUser.getId());
		lower.setState(true);
		lower.setCreateTime(new Date());
		lowerDao.add(lower);
		//userDao.userUpperLevel(7);
		//资金账户
		Account account=new Account();
		account.setAccountState(AccountState.Normal);
		account.setAccountType(AccountType.Customer);
		account.setAccountMoney(new BigDecimal(0));
		account.setAccountKey(md5Key);
		account.setUserId(newUser.getId());
		account.setReducedJiFen(new BigDecimal(0));
		account.setRemainJiFen(new BigDecimal(0));
		account.setTotalJiFen(new BigDecimal(0));
		accountDao.add(account);
		//添加角色
		UserRole userRole =new UserRole();
		userRole.setUserId(newUser.getId());
		userRole.setRoleId(Integer.parseInt(roleId));
		userRoleDao.add(userRole);

		if(role.getId()==AllRole.SystemAdmin.getIntValue()){
			List <DdmShop>  ddmShopList=ddmShopDao.queryPageView(-1,-1,new DdmShop()).getRecords();
			for(DdmShop ddmShop:ddmShopList){
				ShopAdminUser shopAdminUser=new ShopAdminUser();
				shopAdminUser.setShopId(ddmShop.getId());
				shopAdminUser.setUserId(newUser.getId());
				shopAdminUser.setCreateUserId(loginUser.getId());
				shopAdminUser.setCreateTime(new Date());
				shopAdminUserDao.add(shopAdminUser);
			}
		}

		map.put("code",1);
		map.put("msg","success");
		return map;
	}
	/*
	*查找后台用户列表
	* zlq
	*@param  token
	* @param userAccount:用户账号
	* @param  realName：名字
	* @param  userStateValue:用户状态值
	* @param  page:页码
	* @param  userTypeValue:用户类型值
	*
	 */
	public  String getCRMUser(ModelMap map ,String page,String token,String userAccount, String realName,String userStateValue,String userTypeValue){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		User user =new User();
		if (!StringUtils.isEmpty(userAccount)) {
			user.setName(userAccount.trim());
		}
		if (!StringUtils.isEmpty(realName)) {
			user.setRealName(realName.trim());
		}
		if (!StringUtils.isEmpty(userStateValue)) {
			user.setUserStateValue(Integer.parseInt(userStateValue));
		}
		java.util.List<String> userTypelist = new ArrayList<String>();
		if(!StringUtils.isEmpty(userTypeValue)){
			if(UserType.getByIntValue(Integer.parseInt(userTypeValue))!=null){
				userTypelist.add(String.valueOf(UserType.getByIntValue(Integer.parseInt(userTypeValue)).getIntValue()));
			}else {
				userTypelist.add(String.valueOf(UserType.Admin.getIntValue()));
				userTypelist.add(String.valueOf(UserType.Director.getIntValue()));
				userTypelist.add(String.valueOf(UserType.Salesman.getIntValue()));
				userTypelist.add(String.valueOf(UserType.Agency.getIntValue()));
				userTypelist.add(String.valueOf(UserType.Finance.getIntValue()));
			}

		}else {
			userTypelist.add(String.valueOf(UserType.Admin.getIntValue()));
			userTypelist.add(String.valueOf(UserType.Director.getIntValue()));
			userTypelist.add(String.valueOf(UserType.Salesman.getIntValue()));
			userTypelist.add(String.valueOf(UserType.Agency.getIntValue()));
			userTypelist.add(String.valueOf(UserType.Finance.getIntValue()));
		}

		user.setUserTypeList(userTypelist);

		pageview=userDao.queryPageView(pageNo, pageSize,"getCRMUser",user);
		if (pageview != null){
			map.put("datas",convertCRM(pageview.getRecords()));
			map.put("recordsTotal", pageview.getRowCount());
			map.put("totalPage", pageview.getPageCount());
			map.put("pageNow", pageview.getPageNow());
			map.put("code",1);
			map.put("msg","success");
		}
		return  new JSONObject(map).toString();
	}
	public java.util.List<ModelMap> convertCRM(java.util.List<User> users) {
		java.util.List<ModelMap> list = new ArrayList<ModelMap>();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				ModelMap map = buildModelCRM(user);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCRM(User user) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ModelMap model = new ModelMap();
		model.put("id",user.getId());
		model.put("account",user.getName());
		model.put("realNam",user.getRealName());
		if(user.getPhone()!=null){
			model.put("phone",user.getPhone());
		}else {
			model.put("phone","");
		}
		model.put("state",user.getUserState().toString());
		model.put("stateValue",user.getUserStateValue());
		model.put("userType",user.getUserType().toString());
		model.put("userTypeValue",user.getUserTypeValue());
		model.put("createTime",formatter.format(user.getCreateTime()));
		java.util.List<Role> roleList= roleDao.getByUserId(user.getId());
		StringBuffer roleString=new StringBuffer();
		for(Role role :roleList){
			roleString.append(role.getName() +"");
		}
		model.put("role",roleString);
		return model;
	}
	/*
	*对用户进行状态操作
	* zlq
	*@param  token
	* @param id
	 */
	public  String invalidUser(ModelMap map ,String token,String id,UserState userState){
		JedisPool pool = null;
		Jedis jedis = null;
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"updateUserState" );
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", map);
		}else {
			memcached.set(loginUser.getId()+"updateUserState",10,"1");
		}
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
		User user = userDao.getById(Integer.parseInt(id));
		if(user==null){
			return CodeContent.getModelByCode(0, "ID不存在", map);
		}
		if(user.getUserState().equals(userState)){
			return CodeContent.getModelByCode(0, "状态匹配，无需修改", map);
		}
		if(user.getUserType().equals(UserType.Director) || user.getUserType().equals(UserType.Admin) ){
			user.setUserState(userState);
			userDao.modify(user);
		}else {
			return CodeContent.getModelByCode(0, "用户类型不是后台人员或者管理员", map);
		}

			Set<String> userPrivilegeList=jedis.keys(user.getName() + "userPrivilege*");
			if(userPrivilegeList!=null&&userPrivilegeList.size()>0){
				for (String userPrivilege:userPrivilegeList) {//删除之前存入用户缓存的权限
					jedis.del(userPrivilege);
				}
			}
			Set<String> userRolesList=jedis.keys(user.getName() + "userRoles*");
			if(userRolesList!=null&&userRolesList.size()>0){
				for (String userRoles:userRolesList) {//删除之前存入用户角色
					jedis.del(userRoles);
				}
			}


		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		finally {
			pool.returnResource(jedis);
		}
		return CodeContent.getModelByCode(1, "success", map);
	}
	/*
	*对用户进行角色修改
	* zlq
	*@param  token
	* @param id
	* @param roleId
	 */
	public  String updateUserRole(ModelMap map ,String token,String id,String roleId){
		JedisPool pool = null;
		Jedis jedis = null;
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if (StringUtils.isEmpty(roleId)) {
			return CodeContent.getModelByCode(0, "角色ID不能为空", map);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"updateUserRole" );
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", map);
		}else {
			memcached.set(loginUser.getId()+"updateUserRole",10,"1");
		}
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
		Role role=roleDao.getById(Integer.parseInt(roleId));
		if(role==null){
			return CodeContent.getModelByCode(0, "角色ID不存在", map);
		}
		if(role.getIsInit().equals(IsInit.NotAllow)){
			return CodeContent.getModelByCode(0, "该角色不允直接指定给用户", map);
		}
		User user = userDao.getById(Integer.parseInt(id));
		if(user==null){
			return CodeContent.getModelByCode(0, "用户ID不存在", map);
		}
		if(user.getUserState().equals(UserState.Invalid)){
			return CodeContent.getModelByCode(0, "用户已经是无效的", map);
		}
		if(user.getUserType().equals(UserType.Director) || user.getUserType().equals(UserType.Admin) ){
			UserRole userRole=userRoleDao.getByUserId(user.getId());
			if(userRole==null){
				userRole=new UserRole();
				userRole.setUserId(user.getId());
				userRole.setRoleId(role.getId());
				userRoleDao.add(userRole);
			}else {
				userRole.setRoleId(role.getId());
				userRoleDao.modify(userRole);
			}

		}else {
			return CodeContent.getModelByCode(0, "用户类型不是后台人员或者管理员", map);
		}
			Set<String> userPrivilegeList=jedis.keys(user.getName() + "userPrivilege*");
			if(userPrivilegeList!=null&&userPrivilegeList.size()>0){
				for (String userPrivilege:userPrivilegeList) {//删除之前存入用户缓存的权限
					jedis.del(userPrivilege);
				}
			}
			Set<String> userRolesList=jedis.keys(user.getName() + "userRoles*");
			if(userRolesList!=null&&userRolesList.size()>0){
				for (String userRoles:userRolesList) {//删除之前存入用户角色
					jedis.del(userRoles);
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		finally {
			pool.returnResource(jedis);
		}
		return CodeContent.getModelByCode(1, "success", map);
	}

	/*
	*
	* zlq
	* CRM后台用户修改登录密码
	* @param  token
	* @param  password ：加密后的密码
	*
	 */
	public String updateCRMPassword(ModelMap map ,String token,String password){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if (StringUtils.isEmpty(password)) {
			return CodeContent.getModelByCode(0, "密码不能为空", map);
		}
		User user=userDao.getById(loginUser.getId());
		user.setPassword(password);
		userDao.modify(user);
		memcached.delete(token);

		return CodeContent.getModelByCode(1, "success", map);

	}
	/*
*
* zlq
* CRM后台用户初始化登录密码
* @param  token
* @param  id ：用户ID
*
 */
	public String initCRMPassword(ModelMap map ,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if (StringUtils.isEmpty(id)) {
			return CodeContent.getModelByCode(0, "用户ID不能为空", map);
		}
		User user=userDao.getById(Integer.parseInt(id));
		if(user==null){
			return CodeContent.getModelByCode(0, "用户ID不存在", map);
		}
		String password="123456";
		String md5Key = UUID.randomUUID().toString();
		String md5Password = MD5.encryptMD5(password.trim() + md5Key);
		user.setUserKey(md5Key);
		user.setPassword(md5Password);
		userDao.modify(user);

		return CodeContent.getModelByCode(1, "success", map);
	}


    //处理user_upper 为null的用户
	public String getAndHandUser(){
		ModelMap model=new ModelMap();
		List<User> list=userDao.getByUpper();
		Integer count =userDao.countUserByLevel(7,1);
		if(list!=null&&list.size()>0){//未处理
			Lower lower =new Lower();
			model.put("result","需处理用户"+list.size()+"个");
			for (User user:list) {
				user.setUserUpper(1+","+user.getId());
				userDao.modify(user);
				lower.setCreateTime(new Date());
				lower.setLowerUserId(user.getId());
				lower.setUserId(1);
				lower.setState(true);
				lowerDao.add(lower);
				System.out.println("处理：用户id"+user.getId()+" name "+user.getName()+" realName "+user.getRealName());
			}

		}else {
			//已经处理完
			model.put("result","已处理完");
		}
        model.put("count",count);
		return CodeContent.getModelByCode(1,"",model);
	}

	public String updateUserLevel(Integer userId){
		ModelMap model=new ModelMap();
		User user=userDao.getById(userId);
		model.put("userLevel",user.getUserLevel());
		model.put("userLevelValue",user.getUserLevelValue());
//		userDao.userUpperLevel(userId);
//		User user1=userDao.getById(userId);
		model.put("updateUserLevel",user.getUserLevel());
		model.put("updateUserLevelValue",user.getUserLevelValue());
		return CodeContent.getModelByCode(1,"",model);
	}


    //ffl  检验邀请码 返回推荐用户 姓名和手机号
	public Map checkUpperUser(Integer id,String mobile ){
		Map<String,Object>map=new HashMap<String, Object>();
		User user=userDao.getByName(mobile);
		if(user!=null){
			map.put("code",-1);
			map.put("msg","您已经注册过了");
			return map;
		}
		User upperUser=userDao.getById(id);
		if(upperUser==null){
			map.put("code",0);
			map.put("msg","输入的邀请码不存在");
			return map;
		}
		if(!UserState.Normal.equals(upperUser.getUserState())){
			map.put("code",0);
			map.put("msg","此推广邀请码已经无效，请更换有效的邀请码");
			return map;
		}

		map.put("upperPhone",upperUser.getName());
		map.put("upperName",upperUser.getRealName());
		map.put("code",1);
		return map;

	}
    //邀请码注册 登陆
	public String register (Integer id,String mobile ,boolean isdzp){
		User registerUser=userDao.getByName(mobile);
		if(registerUser!=null){
			return CodeContent.getModelByCode(-1,"您已经注册过了",null);
		}
		Sms sms=smsDao.getByMobile(mobile);
		if(sms==null){
			return CodeContent.getModelByCode(0,"系统异常，请联系客服",null);
		}
        Long nowTime=new Date().getTime();
		if(sms.getUseTime()==null){
			return CodeContent.getModelByCode(0,"短信验证码未验证",null);
		}
		Long lastTime=sms.getUseTime().getTime();
		if(nowTime-lastTime>120000){
			return CodeContent.getModelByCode(0,"短信验证码过期",null);
		}

		User upperUser=userDao.getById(id);
		if(upperUser==null){
			return CodeContent.getModelByCode(0,"输入的邀请码不存在",null);
		}
		if(!UserState.Normal.equals(upperUser.getUserState())){
			return CodeContent.getModelByCode(0,"此邀请码已无效，请更换有效的邀请码",null);
		}

//		User user=new User();
//		user.setName(mobile);
//		user.setCreateTime(new Date());
//		user.setRealName(mobile);
//		String userKey= UUID.randomUUID().toString();
//		user.setUserKey(userKey);
//		String password= MD5.encryptMD5(mobile + "12345987");
//		user.setPassword(password);
//		user.setUserState(UserState.Normal);
//		user.setUserType(UserType.Normal);
//		user.setUserLevel(UserLevel.Silver);
//		user.setSex(Sex.Privacy);
//		userDao.add(user);
//		user.setUserUpper(upperUser.getUserUpper()+","+user.getId());
//		userDao.modify(user);
//		//上下级关系
//		Lower lower=new Lower();
//		lower.setUserId(id);
//		lower.setLowerUserId(user.getId());
//		lower.setState(true);
//		lower.setCreateTime(new Date());
//		lowerDao.add(lower);
//		userDao.userUpperLevel(id);
//		//资金账户
//		Account account=new Account();
//		account.setAccountState(AccountState.Normal);
//		account.setAccountType(AccountType.Customer);
//		account.setAccountMoney(new BigDecimal(0));
//		account.setAccountKey(userKey);
//		account.setUserId(user.getId());
//		account.setReducedJiFen(new BigDecimal(0));
//		account.setRemainJiFen(new BigDecimal(0));
//		account.setTotalJiFen(new BigDecimal(0));
//		accountDao.add(account);
//
//
//
		ModelMap model=new ModelMap();
//		//合法用户登陆
//		String	token = MD5.encryptMD5(user.getId() + user.getPassword() + new Date().toString());
//		model.put("token", token);
//		Gson gson = new Gson();
//		model.put("realName",user.getRealName());
//		model.put("userTypeValue",user.getUserTypeValue());
//		model.put("userType",user.getUserType()!=null?user.getUserType().toString():"");
//		memcached.set(token, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
//		//用户最多有三个有效token
//		userTokenLoginCheck(token,user.getId());
		return CodeContent.getModelByCode(1,"sucess", model);
	}

    //获取展示注册红包
	public  String getMyRegisterRedPacket(String token){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		BigDecimal money=new BigDecimal(0).setScale(2,BigDecimal.ROUND_DOWN);
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			String val=jedis.get("register:"+user.getId());
			if(NumberUtils.isNumber(val)){
				money=new BigDecimal(val).setScale(2,BigDecimal.ROUND_DOWN);
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		ModelMap model=new ModelMap();
		model.put("redPacket",money);
		return CodeContent.getModelByCode(1,"",model);
	}

    //领取注册新人红包
	public String updateMyRegisterRedPacket(String token){
		return CodeContent.getModelByCode(1,"",null);
	}

	public User getByWxOpenID(String wxOpenId) {
		return userDao.getByWxOpenID(wxOpenId);
	}

	public User getByQqOpenID(String qqOpenId) {
		return userDao.getByQqOpenID(qqOpenId);
	}


	//邀请码 登陆
	public String registerDDM (String id,String mobile ,String password,String companyCode){
		User registerUser=userDao.getByName(mobile);
		if(registerUser!=null){
			return CodeContent.getModelByCode(-1,"您已经注册过了",null);
		}
		Sms sms=smsDao.getByMobile(mobile);
		if(sms==null){
			return CodeContent.getModelByCode(0,"系统异常，请联系客服",null);
		}
		Long nowTime=new Date().getTime();
		if(sms.getUseTime()==null){
			return CodeContent.getModelByCode(0,"短信验证码未验证",null);
		}
		Long lastTime=sms.getUseTime().getTime();
		if(nowTime-lastTime>120000){
			return CodeContent.getModelByCode(0,"短信验证码过期",null);
		}

		int upperId=1;
		if(NumberUtils.isDigits(id)){
           upperId=NumberUtils.toInt(id);
		}
		int companyC=1;
		if(NumberUtils.isDigits(companyCode)){
			companyC=NumberUtils.toInt(companyCode);
		}
		User upperUser=userDao.getById(upperId);
		User user=new User();
		user.setName(mobile);
		user.setCreateTime(new Date());
		user.setRealName(mobile);
		String userKey= UUID.randomUUID().toString();
		user.setUserKey(userKey);
		String md5Password = MD5.encryptMD5(password.trim() + userKey);
		user.setPassword(md5Password);
		user.setUserState(UserState.Normal);
		user.setUserType(UserType.Normal);
		user.setUserLevel(UserLevel.Silver);
		user.setSex(Sex.Privacy);
        user.setCompanyCode(companyC);
		if(upperId==1){
			userDao.add(user);
			if (user.getId()-1==0){
				user.setUserUpper(user.getId().toString());
				userDao.modify(user);
			}else {
				user.setUserUpper(1+","+user.getId());
				userDao.modify(user);
				//上下级关系
				Lower lower=new Lower();
				lower.setUserId(upperId);
				lower.setLowerUserId(user.getId());
				lower.setState(true);
				lower.setCreateTime(new Date());
				lowerDao.add(lower);
//				userDao.userUpperLevel(upperId);
			}
		}else {
			if (upperUser == null) {
				return CodeContent.getModelByCode(0, "输入的邀请码不存在", null);
			}
			if (!UserState.Normal.equals(upperUser.getUserState())) {
				return CodeContent.getModelByCode(0, "此邀请码已无效，请更换有效的邀请码", null);
			}
			userDao.add(user);
			user.setUserUpper(upperUser.getUserUpper()+","+user.getId());
			userDao.modify(user);
			//上下级关系
			Lower lower=new Lower();
			lower.setUserId(upperId);
			lower.setLowerUserId(user.getId());
			lower.setState(true);
			lower.setCreateTime(new Date());
			lowerDao.add(lower);
			//userDao.userUpperLevel(upperId);
		}


		//资金账户
		Account account=new Account();
		account.setAccountState(AccountState.Normal);
		account.setAccountType(AccountType.Customer);
		account.setAccountMoney(new BigDecimal(0));
		account.setAccountKey(userKey);
		account.setUserId(user.getId());
		account.setReducedJiFen(new BigDecimal(0));
		account.setRemainJiFen(new BigDecimal(0));
		account.setTotalJiFen(new BigDecimal(0));
		accountDao.add(account);

		ModelMap model=new ModelMap();
		//合法用户登陆
		String	token = MD5.encryptMD5(user.getId() + user.getPassword() + new Date().toString());
		model.put("token", token);
		Gson gson = new Gson();
		model.put("realName",user.getRealName());
		model.put("userTypeValue",user.getUserTypeValue());
		model.put("userType",user.getUserType()!=null?user.getUserType().toString():"");
		memcached.set(token, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
		//用户最多有三个有效token
		userTokenLoginCheck(token,user.getId());
		model.put("userId",user.getId());
		return CodeContent.getModelByCode(1,"sucess", model);
	}

	public String getInitRoleUserSelect(ModelMap model,String token){
		PageView pageview = new PageView();

		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		UserRole userRole=userRoleDao.getByUserId(loginUser.getId());
		if(userRole==null){
			return CodeContent.getModelByCode(0, "您没有分配角色", model);
		}
		pageview=userDao.getInitRoleUser(-1,-1,userRole.getRoleList().get(0).getIsInit().getIntValue());

		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convert1(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return new JSONObject(model).toString();
	}

	public List<ModelMap> convert1(List<User> userList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (userList != null && userList.size() > 0) {
			for (User user : userList) {
				ModelMap map = buildModel1(user);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModel1(User user) {
		ModelMap model = new ModelMap();
		model.put("id",user.getId());
		StringBuffer name =new StringBuffer();
		name.append(user.getName());
		name.append("____");
		name.append(user.getRealName());
		name.append("____");
		name.append(user.getRoleList().get(0).getName());
		model.put("name",name.toString());
		return  model;
	}
}